package com.plpm.config;

import java.util.concurrent.Executor;
import java.util.concurrent.ScheduledThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.SchedulingConfigurer;
import org.springframework.scheduling.config.ScheduledTaskRegistrar;

/**
 * 定时任务配置
 *
 * @author PLPM Team
 * @version 1.0
 */
@Configuration
@EnableScheduling
public class ScheduleConfig implements SchedulingConfigurer {

    @Override
    public void configureTasks(ScheduledTaskRegistrar taskRegistrar) {
        taskRegistrar.setScheduler(taskExecutor());
    }

    /**
     * 定时任务执行器
     */
    public Executor taskExecutor() {
        ScheduledThreadPoolExecutor executor = new ScheduledThreadPoolExecutor(
                5,     // 核心线程数
                r -> {                          // 线程工厂
                    Thread thread = new Thread(r);
                    thread.setName("scheduled-task-" + thread.getId());
                    thread.setDaemon(true);
                    return thread;
                }
        );
        
        // 设置线程空闲时间
        executor.setKeepAliveTime(60L, TimeUnit.SECONDS);
        executor.allowCoreThreadTimeOut(true);
        
        // 设置拒绝策略
        executor.setRejectedExecutionHandler(new ScheduledThreadPoolExecutor.CallerRunsPolicy());
        
        return executor;
    }
}
